﻿using Malee;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(ServerConfiguration))]
class ServerConfigurationEditor : Editor
{
    ServerConfiguration configuration;
    public override void OnInspectorGUI()
    {
        if (!configuration)
        {
            configuration = target as ServerConfiguration;
        }
        base.OnInspectorGUI();

        if (GUILayout.Button("保存当前配置为Json"))
        {
            configuration.SaveToJson();
        }
        GUILayout.Space(10);
        GUILayout.Label(@"服务器配置 Json 加载说明：
1. 如果没有服务器的 Json 配置文件，则连接本配置中 active 的服务器，有 json 数据则优先加载Json中的服务器配置。
2. 点击上面的按钮，直接将本配置保存成 json 文件，如已经存在则覆盖之。
3.  编辑器模式下，从 Json 加载的配置数据会直接覆盖本配置文件的数据，打包后覆盖仅发生在内存中。
4.  根据第三条原则，运行时删除json 文件，又会用回本配置文件的配置信息，编辑器模式下则没此效果，可以存Preset。
");
        GUILayout.Space(10);
    }
}
#endif


[CreateAssetMenu(fileName = "ServerConfiguration", menuName = "Configration/Network/ServerConfiguration")]
public class ServerConfiguration : ScriptableObject
{
    private string path = $"{Application.streamingAssetsPath}/ServerConfiguration";


    private void TryLoadConfigurationFromJosn()
    {
        if (Application.isPlaying && File.Exists(Path.Combine(path, "server.json")))
        {
            string json = File.ReadAllText(Path.Combine(path, "server.json"));
            if (!string.IsNullOrEmpty(json))
            {
                Debug.Log("Server Configuration Loaded From json file!");
                ServerArray servers = JsonUtility.FromJson<ServerArray>(json);
                if (null!=servers&&servers.Length>0)
                {
                    this.servers = servers;
                }
            }
        }
    }



    [Reorderable]
    public ServerArray servers = new ServerArray();
    /// <summary>
    /// 获取服务器配置
    /// </summary>
    /// <param name="serverName">指定配置的服务器名称</param>
    /// <returns>服务器IP/PORT 配置信息</returns>
    public ServerAddress GetServerInfo(string serverName)
    {
        TryLoadConfigurationFromJosn();
        ServerAddress server = servers.Find(v => v.name == serverName);
        if (null == server)
        {
            Debug.LogWarning($"不存在备注为：{serverName} 的服务器配置,返回第一个配置信息！");
            server = servers[0];
        }
        return server;
    }
    /// <summary>
    /// 获取服务器配置
    /// </summary>
    /// <returns>服务器IP/PORT 配置信息</returns>
    public ServerAddress GetServerInfo()
    {
        TryLoadConfigurationFromJosn();
        ServerAddress server = servers.Find(v => v.isActive == true);
        if (null == server)
        {
            Debug.LogWarning($"未勾选默认服务器,返回第一个配置信息！");
            server = servers[0];
        }
        return server;
    }

    internal void SaveToJson()
    {
        if (!Directory.Exists(path)) //默认有一个这样的文件夹吧
        {
            Directory.CreateDirectory(path);
        }
        using (StreamWriter writer = File.CreateText(Path.Combine(path, "server.json")))
        {
            writer.WriteLine(JsonUtility.ToJson(servers));
        }
#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
    }
    #region Assistant Class
    /// <summary>
    /// 服务器地址
    /// </summary>
    [Serializable]
    public class ServerAddress
    {
        /// <summary>
        ///  备注服务器名称
        /// </summary>
        public string name;
        /// <summary>
        /// 服务器地址，支持url 
        /// </summary>
        public string host;
        public bool isActive;
        /// <summary>
        /// 端口
        /// </summary>
        [Reorderable] public PortArray ports;
    }
    [Serializable]
    public class Port
    {
        /// <summary>
        ///  备注端口名称
        /// </summary>
        public string name;
        /// <summary>
        /// 配置的端口号
        /// </summary>
        public int port;
    }
    [Serializable] public class ServerArray : ReorderableArray<ServerAddress> { }
    [Serializable] public class PortArray : ReorderableArray<Port> { }
    #endregion
}
